import { isString } from 'lodash-es'

export function callNewPage(
  opts?:
    | {
    href: string
    timeout?: number
    target?: '_blank' | '_self' | '_parent' | '_top' | null
  }
    | string,
) {
  const _opts = (() => {
    const defuOpts = { href: '', timeout: 1000, target: '' }
    if (isString(opts)) {
      return { ...defuOpts, href: opts }
    }
    else {
      return { ...defuOpts, ...opts }
    }
  })()

  return new Promise<void>((resolve, reject) => {
    const a = document.createElement('a')
    a.href = _opts.href
    a.target = _opts.target ?? ''
    setTimeout(() => {
      reject(new Error(`[callNewPage]: call ${_opts.href} timeout`))
    }, _opts.timeout)
    window.addEventListener(
      'visibilitychange',
      () => resolve(),
      { once: true },
    )
    a.click()
  })
}
